import React, { PureComponent, Fragment } from 'react';
import { Card, Form, Row, Input, Button, Table, Divider, Popconfirm, message } from 'antd';
import { connect } from 'dva';
import lodash from 'lodash';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import Ellipsis from '../../components/Ellipsis';
import RoleManageAdd from './RoleManageAdd';
import RoleManageUpdate from './RoleManageUpdate';
import RoleBindPermission from './RoleBindPermission';
import { SorterOrderMapper } from '../../utils/enum';
import { cutOffStr } from '../../utils/utils';
// import classNames from 'classnames';
import styles from './RoleManage.less';

@connect(({ RoleManageModel, GlobalEnumModel, loading }) => ({
  RoleManageModel,
  GlobalEnumModel,
  queryLoading: loading.effects['RoleManageModel/findByPage'],
  addRoleLoading: loading.effects['RoleManageModel/addRole'],
  updateRoleLoading: loading.effects['RoleManageModel/updateRole'],
  roleBindPermissionLoading: loading.effects['RoleManageModel/roleBindPermission'],
}))
@Form.create()
export default class RoleManage extends PureComponent {

  // 数据初始化
  componentDidMount() {
    this.findByPage();
  }

  // 查询数据
  findByPage = (e) => {
    if (e) e.preventDefault();
    const { dispatch, form } = this.props;
    const queryParam = form.getFieldsValue();
    dispatch({ type: 'RoleManageModel/findByPage', payload: { ...queryParam, pageNo: 0 } });
    dispatch({ type: 'RoleManageModel/save', payload: { selectedRowKeys: [] } });
  }

  // 表格数据过滤或跳页
  handleTableChange = (pagination, _, sorter) => {
    const { dispatch, RoleManageModel } = this.props;
    const queryParam = { ...RoleManageModel.queryParam, pageNo: pagination.current, pageSize: pagination.pageSize };
    // 排序
    if (sorter.field) {
      const sorterMapper = {};
      queryParam.orderField = sorterMapper[sorter.field];
      queryParam.sort = SorterOrderMapper[sorter.order];
    } else {
      queryParam.orderField = undefined;
      queryParam.sort = undefined;
    }
    dispatch({ type: 'RoleManageModel/findByPage', payload: queryParam });
  }

  // 查询表单
  queryForm() {
    const { form: { getFieldDecorator }, queryLoading, RoleManageModel: { queryParam } } = this.props;
    return (
      <Form onSubmit={this.findByPage} layout="inline" className={styles.queryForm}>
        <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
          <Form.Item label="角色名称">
            {getFieldDecorator('name', { initialValue: queryParam.username })(
              <Input placeholder="角色名称(模糊匹配)" />
            )}
          </Form.Item>
          <Form.Item className={styles.formItemButton}>
            <Button type="primary" htmlType="submit" disabled={queryLoading}>查询</Button>
          </Form.Item>
        </Row>
      </Form>
    );
  }

  // 功能按钮
  actionButton() {
    const { dispatch, RoleManageModel: { selectedRowKeys }, queryLoading } = this.props;
    const disabled = queryLoading || (selectedRowKeys && selectedRowKeys.length <= 0);
    return (
      <Fragment>
        <Button.Group style={{ marginBottom: 8 }}>
          <Button onClick={() => dispatch({ type: 'RoleManageModel/save', payload: { showAddRole: true } })}>
            新增角色
          </Button>
          <Button
            disabled={disabled}
            onClick={() => {
              dispatch({ type: 'GlobalEnumModel/allSysName' });
              dispatch({ type: 'RoleManageModel/save', payload: { showRoleBindPermission: true } });
              this.roleBindPermissionInit(selectedRowKeys);
            }}
          >
            分配权限
          </Button>
        </Button.Group>
      </Fragment>
    );
  }

  // 数据表格
  getTable() {
    const { dispatch, RoleManageModel, queryLoading } = this.props;
    const columns = [
      {
        title: '角色名称', dataIndex: 'name', width: 300,
        render: val => {
          const lable = cutOffStr(val, 34);
          return <a title={val === lable ? undefined : val}>{lable}</a>;
        },
      },
      { title: '说明', dataIndex: 'description', width: undefined, render: val => <Ellipsis title={val} lines={1}>{val}</Ellipsis> },
      { title: '创建时间', dataIndex: 'createAt', width: 160 },
      { title: '更新时间', dataIndex: 'updateAt', width: 160 },
      {
        title: '操作', align: 'center', key: 'action', width: 150,
        render: (_, record) => (
          <Fragment>
            <a onClick={() => {
              dispatch({ type: 'GlobalEnumModel/allSysName' });
              dispatch({ type: 'RoleManageModel/save', payload: { showRoleBindPermission: true, selectedRowKeys: [{ id: record.id, name: record.name }] } });
              this.roleBindPermissionInit([{ id: record.id, name: record.name }]);
            }}
            >
              授权
            </a>
            <Divider type="vertical" />
            <a
              onClick={() => {
                dispatch({ type: 'RoleManageModel/save', payload: { showUpdateRole: true, updateRole: record } });
              }}
            >
              编辑
            </a>
            <Divider type="vertical" />
            <Popconfirm
              placement="left"
              title={`确定删除该角色(${record.name})?`}
              okText="删除"
              cancelText="取消"
              onConfirm={() => dispatch({ type: 'RoleManageModel/delRole', payload: { name: record.name } })}
            >
              <a>删除</a>
            </Popconfirm>
          </Fragment>
        ),
      },
    ];
    return (
      <Table
        size="middle"
        bordered={true}
        rowKey={record => record.id}
        rowSelection={{
          fixed: false,
          selectedRowKeys: RoleManageModel.selectedRowKeys.map(item => item.id),
          onChange: (_, selectedRows) => {
            const max = 50;
            if (selectedRows.length > max) {
              message.warning(`最多只能选择${max}个角色，当前选择${selectedRows.length}个`);
              return;
            }
            const selectedRowKeys = selectedRows.map(item => ({ id: item.id, name: item.name }));
            dispatch({ type: 'RoleManageModel/save', payload: { selectedRowKeys } });
          },
        }}
        columns={columns}
        loading={queryLoading}
        dataSource={RoleManageModel.data}
        pagination={RoleManageModel.pagination}
        onChange={this.handleTableChange}
      />
    );
  }

  // 删除选择的角色
  delSelectRole = (roleId) => {
    const { dispatch, RoleManageModel } = this.props;
    const selectedRowKeys = lodash.filter(RoleManageModel.selectedRowKeys, role => roleId !== role.id);
    dispatch({ type: 'RoleManageModel/save', payload: { selectedRowKeys } });
  }

  render() {
    const { dispatch, addRoleLoading, updateRoleLoading, roleBindPermissionLoading, RoleManageModel, GlobalEnumModel } = this.props;
    return (
      <PageHeaderLayout>
        <Card bordered={false}>
          <div>
            {this.queryForm()}
          </div>
          {this.actionButton()}
          {this.getTable()}
        </Card>
        <RoleManageAdd
          roleData={RoleManageModel.addRole}
          saveForm={form => { this.addRoleForm = form }}
          visible={RoleManageModel.showAddRole}
          confirmLoading={addRoleLoading}
          onCancel={() => {
            dispatch({ type: 'RoleManageModel/save', payload: { showAddRole: false } });
            this.addRoleForm.resetFields();
          }}
          onOk={roleData => {
            dispatch({
              type: 'RoleManageModel/addRole',
              payload: roleData,
              successCallBack: result => {
                message.success(`新增角色成功 -> ${result.name}`);
                this.addRoleForm.resetFields();
              },
            });
          }}
        />
        <RoleManageUpdate
          roleData={RoleManageModel.updateRole}
          saveForm={form => { this.updateRoleForm = form }}
          visible={RoleManageModel.showUpdateRole}
          confirmLoading={updateRoleLoading}
          onCancel={() => {
            dispatch({ type: 'RoleManageModel/save', payload: { showUpdateRole: false } });
            this.updateRoleForm.resetFields();
          }}
          onOk={(name, roleData) => {
            dispatch({
              type: 'RoleManageModel/updateRole',
              payload: { name, roleData },
              successCallBack: result => {
                message.success(`更新角色成功 -> ${result.name}`);
                this.updateRoleForm.resetFields();
              },
            });
          }}
        />
        <RoleBindPermission
          roleList={RoleManageModel.selectedRowKeys}
          sysNameList={GlobalEnumModel.sysNameList}
          resetStateFuc={resetState => { this.roleBindPermissionReset = resetState }}
          initVisibleDataFuc={initVisibleData => { this.roleBindPermissionInit = initVisibleData }}
          visible={RoleManageModel.showRoleBindPermission}
          confirmLoading={roleBindPermissionLoading}
          delSelectRole={this.delSelectRole}
          onCancel={() => {
            dispatch({ type: 'RoleManageModel/save', payload: { showRoleBindPermission: false } });
            this.roleBindPermissionReset();
          }}
          onOk={(roleNameList, permissionStrList) => {
            dispatch({
              type: 'RoleManageModel/roleBindPermission',
              payload: { roleNameList, permissionStrList },
              successCallBack: result => {
                message.success(`成功 -> ${result.length}个角色 ${result[0].permissionList.length}个权限`);
                this.roleBindPermissionReset();
              },
            });
          }}
        />
      </PageHeaderLayout>
    );
  }
}
